<template>
  <div class="shop-container">
    <div class="page-header">
      <h1>🛍 宠物商城</h1>
      <p>为您的爱宠挑选优质商品</p>
    </div>

    <!-- 分类导航 -->
    <el-card class="category-card">
      <el-tabs v-model="activeCategory" @tab-click="handleCategoryChange">
        <el-tab-pane label="全部商品" name="all"></el-tab-pane>
        <el-tab-pane label="狗粮" name="dog-food"></el-tab-pane>
        <el-tab-pane label="猫粮" name="cat-food"></el-tab-pane>
        <el-tab-pane label="玩具用品" name="toy"></el-tab-pane>
        <el-tab-pane label="日常用品" name="daily"></el-tab-pane>
        <el-tab-pane label="医疗保健" name="health"></el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 筛选和排序 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="价格区间">
          <el-select v-model="searchForm.priceRange" placeholder="请选择" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="50元以下" value="0-50"></el-option>
            <el-option label="50-100元" value="50-100"></el-option>
            <el-option label="100-200元" value="100-200"></el-option>
            <el-option label="200元以上" value="200-"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序方式">
          <el-select v-model="searchForm.sortBy" placeholder="请选择">
            <el-option label="默认排序" value="default"></el-option>
            <el-option label="价格从低到高" value="price-asc"></el-option>
            <el-option label="价格从高到低" value="price-desc"></el-option>
            <el-option label="销量最高" value="sales"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商品列表 -->
    <div class="product-list">
      <el-row :gutter="20">
        <el-col :span="6" v-for="product in productList" :key="product.id">
          <el-card :body-style="{ padding: '0px' }" shadow="hover" class="product-card">
            <div class="product-image-wrapper" @click="handleViewDetail(product)">
              <img :src="product.image" class="product-image">
              <el-tag v-if="product.tag" type="danger" class="product-tag">{{ product.tag }}</el-tag>
            </div>
            <div class="product-content">
              <h3 @click="handleViewDetail(product)">{{ product.name }}</h3>
              <p class="product-desc">{{ product.description }}</p>
              <div class="product-footer">
                <div class="price-info">
                  <span class="price">¥{{ product.price }}</span>
                  <span class="sales">已售{{ product.sales }}</span>
                </div>
                <div class="action-buttons">
                  <el-button type="warning" size="small" icon="el-icon-shopping-cart-2"
                             @click="handleAddToCart(product)">
                    加购
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[8, 16, 24, 32]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total">
      </el-pagination>
    </div>

    <!-- 购物车浮动按钮 -->
    <div class="cart-float-btn" @click="goToCart">
      <el-badge :value="cartCount" :max="99" class="cart-badge">
        <i class="el-icon-shopping-cart-2"></i>
      </el-badge>
    </div>
  </div>
</template>

<script>
import { getProductList } from '@/api/product'
import { addToCart } from '@/api/cart'

export default {
  name: 'Shop',
  data () {
    return {
      loading: false,
      activeCategory: 'all',
      searchForm: {
        name: '',
        priceRange: '',
        sortBy: 'default'
      },
      productList: [],
      pagination: {
        currentPage: 1,
        pageSize: 8,
        total: 0
      },
      cartCount: 0
    }
  },
  created () {
    this.loadProductList()
  },
  methods: {
    loadProductList () {
      this.loading = true
      const params = {
        pageNum: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      }
      // 添加分类筛选 - 根据不同分类使用不同的查询方式
      if (this.activeCategory && this.activeCategory !== 'all') {
        // 狗粮和猫粮使用 category 参数进行模糊查询
        if (this.activeCategory === 'dog-food') {
          params.category = '狗粮'
          console.log('分类查询 - 狗粮（模糊查询）:', params.category)
        } else if (this.activeCategory === 'cat-food') {
          params.category = '猫粮'
          console.log('分类查询 - 猫粮（模糊查询）:', params.category)
        } else {
          // 其他分类使用 categoryId
          const categoryMap = {
            'toy': 2,     // 玩具用品
            'daily': 3,   // 日常用品
            'health': 4   // 医疗保健
          }
          const categoryId = categoryMap[this.activeCategory]
          if (categoryId) {
            params.categoryId = categoryId
            console.log('分类查询 - categoryId:', params.categoryId)
          }
        }
      }
      // 添加关键词搜索 - 使用 productName 参数（接口文档标准）
      if (this.searchForm.name) {
        params.productName = this.searchForm.name
        console.log('商品名称搜索:', params.productName)
      }
      // 处理价格范围
      if (this.searchForm.priceRange) {
        const priceRange = this.searchForm.priceRange
        if (priceRange === '0-50') {
          params.minPrice = 0
          params.maxPrice = 50
        } else if (priceRange === '50-100') {
          params.minPrice = 50
          params.maxPrice = 100
        } else if (priceRange === '100-200') {
          params.minPrice = 100
          params.maxPrice = 200
        } else if (priceRange === '200-') {
          params.minPrice = 200
        }
      }
      // 处理排序
      if (this.searchForm.sortBy && this.searchForm.sortBy !== 'default') {
        if (this.searchForm.sortBy === 'price-asc') {
          params.orderBy = 'price'
          params.order = 'asc'
        } else if (this.searchForm.sortBy === 'price-desc') {
          params.orderBy = 'price'
          params.order = 'desc'
        } else if (this.searchForm.sortBy === 'sales') {
          params.orderBy = 'sales'
          params.order = 'desc'
        }
      }
      getProductList(params).then(res => {
        this.loading = false
        if (res && res.data) {
          const data = res.data.records || res.data.list || res.data || []
          console.log('商品列表原始数据:', data.length > 0 ? data.slice(0, 2) : '无数据') // 调试日志
          this.productList = data.map(item => ({
            id: item.id,
            // 商品名称 - 优先使用 productName（接口文档标准字段）
            name: item.productName || item.product_name || item.name || '未命名商品',
            // 商品描述
            description: item.description || '',
            // 价格
            price: item.price || 0,
            // 销量 - 使用 soldQuantity（接口文档标准字段）
            sales: item.soldQuantity || item.sold_quantity || item.sales || 0,
            // 标签 - 根据库存判断
            tag: item.stockQuantity > 100 || item.stock_quantity > 100 ? '热销' : '',
            // 图片 - 优先使用 mainImage（接口文档标准字段）
            image: item.mainImage || item.main_image || item.image || require('@/assets/logo.png')
          }))
          this.pagination.total = res.data.total || data.length
          console.log('处理后的商品数据:', this.productList.length, '条') // 调试日志
          if (this.productList.length === 0) {
            this.$message.warning({ message: '暂无商品数据', duration: 800 })
          }
        }
      }).catch(err => {
        this.loading = false
        console.error('加载商品列表失败：', err)
        this.$message.error({ message: '加载商品列表失败', duration: 800 })
      })
    },
    handleCategoryChange (tab) {
      console.log('切换分类', tab.name)
      this.loadProductList()
    },
    handleSearch () {
      console.log('搜索', this.searchForm)
      this.loadProductList()
    },
    handleReset () {
      this.searchForm = {
        name: '',
        priceRange: '',
        sortBy: 'default'
      }
      this.loadProductList()
    },
    handleViewDetail (product) {
      this.$router.push({ path: '/user/product-detail', query: { id: product.id } })
    },
    handleAddToCart (product) {
      addToCart({
        productId: product.id,
        quantity: 1
      }).then(res => {
        this.cartCount++
        this.$message.success({ message: `${product.name} 已加入购物车`, duration: 800 })
      }).catch(err => {
        console.error('加入购物车失败：', err)
        this.$message.error({ message: '加入购物车失败', duration: 800 })
      })
    },
    goToCart () {
      this.$router.push('/user/cart')
    },
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.loadProductList()
    },
    handleCurrentChange (val) {
      this.pagination.currentPage = val
      this.loadProductList()
    }
  }
}
</script>

<style scoped>
.shop-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 80px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
  padding: 30px;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
  border-radius: 8px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  font-size: 32px;
}

.category-card, .filter-card {
  margin-bottom: 20px;
}

.product-list {
  margin-bottom: 20px;
}

.product-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  height: 100%;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.product-image-wrapper {
  position: relative;
  cursor: pointer;
}

.product-image {
  width: 100%;
  height: 220px;
  object-fit: cover;
}

.product-tag {
  position: absolute;
  top: 10px;
  left: 10px;
}

.product-content {
  padding: 15px;
}

.product-content h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-content h3:hover {
  color: #409EFF;
}

.product-desc {
  font-size: 12px;
  color: #999;
  margin: 0 0 15px 0;
  height: 36px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-footer {
  border-top: 1px solid #eee;
  padding-top: 12px;
}

.price-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}

.sales {
  font-size: 12px;
  color: #999;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.action-buttons .el-button {
  flex: 1;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
}

.cart-float-btn {
  position: fixed;
  right: 40px;
  bottom: 40px;
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  transition: all 0.3s;
  z-index: 1000;
}

.cart-float-btn:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4);
}

.cart-float-btn i {
  font-size: 28px;
  color: white;
}

.cart-badge {
  line-height: 1;
}
</style>
